package com.flower.wholesale.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;

/** 
 * @author: 姚雁飞
 * @desc: 控制层父类
 * @date: 2019年9月2日 下午3:29:35
 * @since JDK1.8 
 * @see com.dingliang.agent.controller
 */
public abstract class BaseController{
	@Autowired
	protected HttpServletRequest request;
	@Autowired
	protected HttpSession session;
	@Autowired
	protected HttpServletResponse response;
	
	/**
	 * @author: 姚雁飞
	 * @desc: 获取所有的请求参数
	 * @date: 2015年5月28日 下午2:33:36
	 * @param request
	 * @return
	 */
	public Map<String, String> getSimpleRequestParamMap(
			HttpServletRequest request) {
		Map<String, String[]> srcParamMap = request.getParameterMap();
		Map<String, String> paramMap = new HashMap<String, String>();
		if (srcParamMap != null && srcParamMap.size() > 0) {
			for (String key : srcParamMap.keySet()) {
				if (srcParamMap.get(key).length == 1) {
					String value = srcParamMap.get(key)[0];
					paramMap.put(key, StringUtils.trimToEmpty(value));
				} else {
					paramMap.put(key, srcParamMap.get(key).toString());
				}
			}
		}
		return paramMap;

	}
	/**
	 * 
	 * @author: 姚雁飞
	 * @desc: 将map集合转换为json对象并返回
	 * @date: 2015年5月28日 下午2:50:21
	 * @param response
	 * @param data
	 * @throws IOException
	 */
	public static void responseJson(HttpServletResponse response,
			Map<String, String> data) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		JSONObject jsonObject = new JSONObject();
		if (data != null && data.size() > 0) {
			for (Map.Entry<String, String> entry : data.entrySet()) {
				jsonObject.put(entry.getKey(), entry.getValue());
			}
		}
		response.getWriter().write(jsonObject.toString());
	}
	public static void responseJson(HttpServletResponse response,
			JSONObject jsonObject) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		response.getWriter().write(jsonObject.toString());
	}
}
